package com.network;

import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;

/**
 * @ClassName: HttpServers
 * @Description: HTTP服务，接收http请求，并处理返回响应
 * @author yanghao
 * @date 2015年1月30日 下午4:32:35
 */
public class HttpServers extends Thread {

	public enum Server {
		running, stop;
	}

	// 状态，0启动，1停止
	private Server status = Server.stop;
	private HttpServer httpserver;
	// 监听端口
	private int port;
	// 并发数 能同时接受n个请求
	private int MAX = 50;

	private HttpServers() {

	}

	private static HttpServers server;

	/**
	 * @Title: getInstance
	 * @Description: 单例，确保只能一个实例
	 * @param @return 设定文件
	 * @return HttpServers 返回类型
	 * @throws
	 */
	public static HttpServers getInstance() {
		if (server == null) {
			server = new HttpServers();
		}
		return server;
	}

	/**
	 * @Title: isRun
	 * @Description: http服务是否已启动
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	public boolean isRun() {
		if (status == Server.stop) {
			return false;
		}
		return true;
	}

	/**
	 * @Description 启动服务，接收来自客户端的http请求
	 * @param @param port
	 * @param @param max
	 * @param @param serverName
	 * @param @param handler
	 * @param @throws Exception 参数
	 * @return void 返回类型
	 * @throws
	 */
	public void startService(String serverName, int port, HttpHandler handler) throws Exception {
		this.startService(serverName, port, MAX, handler);
	}

	public void startService(String serverName, int port, int max, HttpHandler handler) throws Exception {
		// 只能启动一次
		if (!isRun()) {
			HttpServerProvider provider = HttpServerProvider.provider();
			httpserver = provider.createHttpServer(new InetSocketAddress(port), max);
			httpserver.createContext("/" + serverName, handler);
			httpserver.setExecutor(null);
			httpserver.start();
			status = Server.running;
			this.port = port;
		} else {
			throw new Exception("server running now");
		}
	}

	public int getPort() {
		return this.port;
	}

}